import { apiService } from './api';

// 用户相关类型定义
export interface User {
  id: string;
  username: string;
  email: string;
  phone?: string;
  firstName: string;
  lastName: string;
  displayName: string;
  avatar?: string;
  status: 'active' | 'inactive' | 'locked' | 'pending';
  emailVerified: boolean;
  phoneVerified: boolean;
  lastLoginAt?: string;
  lastLoginIp?: string;
  loginCount: number;
  failedLoginAttempts: number;
  lockedAt?: string;
  lockedUntil?: string;
  passwordChangedAt?: string;
  mustChangePassword: boolean;
  roles: UserRole[];
  departments: UserDepartment[];
  permissions: string[];
  profile: UserProfile;
  preferences: UserPreferences;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  updatedBy: string;
}

export interface UserRole {
  id: string;
  name: string;
  code: string;
  description: string;
  permissions: string[];
  isDefault: boolean;
  assignedAt: string;
  assignedBy: string;
}

export interface UserDepartment {
  id: string;
  name: string;
  code: string;
  fullPath: string;
  position?: string;
  isManager: boolean;
  isPrimary: boolean;
  assignedAt: string;
  assignedBy: string;
}

export interface UserProfile {
  title?: string;
  bio?: string;
  location?: string;
  website?: string;
  socialLinks?: {
    linkedin?: string;
    github?: string;
    twitter?: string;
  };
  skills?: string[];
  languages?: string[];
  timezone?: string;
  dateFormat?: string;
  timeFormat?: string;
}

export interface UserPreferences {
  theme: 'light' | 'dark' | 'auto';
  language: string;
  notifications: {
    email: boolean;
    push: boolean;
    sms: boolean;
    inApp: boolean;
  };
  privacy: {
    profileVisible: boolean;
    emailVisible: boolean;
    phoneVisible: boolean;
  };
}

export interface UserSearchParams {
  keyword?: string;
  status?: User['status'];
  roleId?: string;
  departmentId?: string;
  emailVerified?: boolean;
  phoneVerified?: boolean;
  lastLoginRange?: {
    start: string;
    end: string;
  };
  createdRange?: {
    start: string;
    end: string;
  };
  page?: number;
  size?: number;
  sortBy?: 'username' | 'email' | 'displayName' | 'lastLoginAt' | 'createdAt';
  sortOrder?: 'asc' | 'desc';
}

export interface CreateUserRequest {
  username: string;
  email: string;
  phone?: string;
  firstName: string;
  lastName: string;
  password?: string;
  mustChangePassword?: boolean;
  roles?: string[];
  departments?: {
    departmentId: string;
    position?: string;
    isManager?: boolean;
    isPrimary?: boolean;
  }[];
  profile?: Partial<UserProfile>;
  sendWelcomeEmail?: boolean;
}

export interface UpdateUserRequest {
  email?: string;
  phone?: string;
  firstName?: string;
  lastName?: string;
  status?: User['status'];
  roles?: string[];
  departments?: {
    departmentId: string;
    position?: string;
    isManager?: boolean;
    isPrimary?: boolean;
  }[];
  profile?: Partial<UserProfile>;
  preferences?: Partial<UserPreferences>;
}

export interface PasswordResetRequest {
  userId: string;
  newPassword?: string;
  mustChangePassword?: boolean;
  sendNotification?: boolean;
}

export interface UserImportData {
  username: string;
  email: string;
  phone?: string;
  firstName: string;
  lastName: string;
  roles?: string[];
  departments?: string[];
  profile?: Partial<UserProfile>;
}

export interface UserStats {
  total: number;
  active: number;
  inactive: number;
  locked: number;
  pending: number;
  emailVerified: number;
  phoneVerified: number;
  recentLogins: number;
  newUsers: number;
  byRole: Record<string, number>;
  byDepartment: Record<string, number>;
}

export interface UserActivity {
  id: string;
  userId: string;
  userName: string;
  action: string;
  description: string;
  ipAddress: string;
  userAgent: string;
  location?: string;
  metadata?: Record<string, any>;
  createdAt: string;
}

// 用户管理服务类
class UserService {
  // 获取用户列表
  async getUsers(params?: UserSearchParams): Promise<{
    content: User[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/users', params);
  }

  // 获取用户详情
  async getUser(id: string): Promise<User> {
    return apiService.get(`/users/${id}`);
  }

  // 根据用户名获取用户
  async getUserByUsername(username: string): Promise<User> {
    return apiService.get(`/users/username/${username}`);
  }

  // 创建用户
  async createUser(userData: CreateUserRequest): Promise<User> {
    return apiService.post('/users', userData);
  }

  // 更新用户
  async updateUser(id: string, userData: UpdateUserRequest): Promise<User> {
    return apiService.put(`/users/${id}`, userData);
  }

  // 删除用户
  async deleteUser(id: string): Promise<void> {
    return apiService.delete(`/users/${id}`);
  }

  // 批量删除用户
  async deleteUsers(ids: string[]): Promise<void> {
    return apiService.post('/users/batch/delete', { ids });
  }

  // 更新用户状态
  async updateUserStatus(id: string, status: User['status']): Promise<User> {
    return apiService.put(`/users/${id}/status`, { status });
  }

  // 批量更新用户状态
  async updateUsersStatus(ids: string[], status: User['status']): Promise<void> {
    return apiService.put('/users/batch/status', { ids, status });
  }

  // 锁定用户
  async lockUser(id: string, reason?: string, duration?: number): Promise<User> {
    return apiService.post(`/users/${id}/lock`, { reason, duration });
  }

  // 解锁用户
  async unlockUser(id: string): Promise<User> {
    return apiService.post(`/users/${id}/unlock`);
  }

  // 重置密码
  async resetPassword(request: PasswordResetRequest): Promise<{ temporaryPassword?: string }> {
    return apiService.post(`/users/${request.userId}/reset-password`, request);
  }

  // 修改密码
  async changePassword(id: string, oldPassword: string, newPassword: string): Promise<void> {
    return apiService.put(`/users/${id}/change-password`, {
      oldPassword,
      newPassword
    });
  }

  // 强制修改密码
  async forceChangePassword(id: string, newPassword: string): Promise<void> {
    return apiService.put(`/users/${id}/force-change-password`, {
      newPassword
    });
  }

  // 分配角色
  async assignRoles(id: string, roleIds: string[]): Promise<User> {
    return apiService.put(`/users/${id}/roles`, { roleIds });
  }

  // 移除角色
  async removeRoles(id: string, roleIds: string[]): Promise<User> {
    return apiService.post(`/users/${id}/roles/remove`, { roleIds });
  }

  // 分配部门
  async assignDepartments(id: string, departments: {
    departmentId: string;
    position?: string;
    isManager?: boolean;
    isPrimary?: boolean;
  }[]): Promise<User> {
    return apiService.put(`/users/${id}/departments`, { departments });
  }

  // 移除部门
  async removeDepartments(id: string, departmentIds: string[]): Promise<User> {
    return apiService.post(`/users/${id}/departments/remove`, { departmentIds });
  }

  // 上传头像
  async uploadAvatar(id: string, file: File): Promise<{ avatarUrl: string }> {
    const formData = new FormData();
    formData.append('avatar', file);
    return apiService.post(`/users/${id}/avatar`, formData);
  }

  // 删除头像
  async deleteAvatar(id: string): Promise<void> {
    return apiService.delete(`/users/${id}/avatar`);
  }

  // 更新用户资料
  async updateProfile(id: string, profile: Partial<UserProfile>): Promise<User> {
    return apiService.put(`/users/${id}/profile`, profile);
  }

  // 更新用户偏好设置
  async updatePreferences(id: string, preferences: Partial<UserPreferences>): Promise<User> {
    return apiService.put(`/users/${id}/preferences`, preferences);
  }

  // 发送邮箱验证
  async sendEmailVerification(id: string): Promise<void> {
    return apiService.post(`/users/${id}/send-email-verification`);
  }

  // 验证邮箱
  async verifyEmail(token: string): Promise<void> {
    return apiService.post('/users/verify-email', { token });
  }

  // 发送手机验证
  async sendPhoneVerification(id: string): Promise<void> {
    return apiService.post(`/users/${id}/send-phone-verification`);
  }

  // 验证手机
  async verifyPhone(id: string, code: string): Promise<void> {
    return apiService.post(`/users/${id}/verify-phone`, { code });
  }

  // 获取用户统计
  async getUserStats(): Promise<UserStats> {
    return apiService.get('/users/stats');
  }

  // 获取用户活动日志
  async getUserActivities(userId?: string, params?: {
    action?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    size?: number;
  }): Promise<{
    content: UserActivity[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    const url = userId ? `/users/${userId}/activities` : '/users/activities';
    return apiService.get(url, params);
  }

  // 导入用户
  async importUsers(file: File, options?: {
    skipDuplicates?: boolean;
    updateExisting?: boolean;
    sendWelcomeEmail?: boolean;
  }): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    if (options) {
      formData.append('options', JSON.stringify(options));
    }
    return apiService.post('/users/import', formData);
  }

  // 导出用户
  async exportUsers(params?: {
    format: 'csv' | 'excel' | 'json';
    fields?: string[];
    filters?: UserSearchParams;
  }): Promise<Blob> {
    return apiService.get('/users/export', params);
  }

  // 批量操作
  async batchOperation(operation: {
    type: 'assign_roles' | 'remove_roles' | 'assign_departments' | 'remove_departments' | 'update_status';
    userIds: string[];
    data: any;
  }): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    return apiService.post('/users/batch/operation', operation);
  }

  // 检查用户名是否可用
  async checkUsernameAvailability(username: string, excludeUserId?: string): Promise<{ available: boolean }> {
    return apiService.get('/users/check-username', { username, excludeUserId });
  }

  // 检查邮箱是否可用
  async checkEmailAvailability(email: string, excludeUserId?: string): Promise<{ available: boolean }> {
    return apiService.get('/users/check-email', { email, excludeUserId });
  }

  // 获取用户权限
  async getUserPermissions(id: string): Promise<string[]> {
    return apiService.get(`/users/${id}/permissions`);
  }

  // 检查用户权限
  async checkUserPermission(id: string, permission: string): Promise<{ hasPermission: boolean }> {
    return apiService.get(`/users/${id}/check-permission`, { permission });
  }

  // 获取用户会话
  async getUserSessions(id: string): Promise<{
    id: string;
    deviceInfo: string;
    ipAddress: string;
    location?: string;
    lastActivity: string;
    isActive: boolean;
  }[]> {
    return apiService.get(`/users/${id}/sessions`);
  }

  // 终止用户会话
  async terminateUserSession(userId: string, sessionId: string): Promise<void> {
    return apiService.delete(`/users/${userId}/sessions/${sessionId}`);
  }

  // 终止用户所有会话
  async terminateAllUserSessions(userId: string): Promise<void> {
    return apiService.delete(`/users/${userId}/sessions`);
  }

  // 获取在线用户
  async getOnlineUsers(): Promise<{
    id: string;
    username: string;
    displayName: string;
    avatar?: string;
    lastActivity: string;
    status: string;
  }[]> {
    return apiService.get('/users/online');
  }

  // 发送系统通知给用户
  async sendNotificationToUser(userId: string, notification: {
    title: string;
    content: string;
    type?: 'info' | 'success' | 'warning' | 'error';
    channels?: ('email' | 'push' | 'sms')[];
  }): Promise<void> {
    return apiService.post(`/users/${userId}/notify`, notification);
  }

  // 批量发送通知
  async sendNotificationToUsers(userIds: string[], notification: {
    title: string;
    content: string;
    type?: 'info' | 'success' | 'warning' | 'error';
    channels?: ('email' | 'push' | 'sms')[];
  }): Promise<void> {
    return apiService.post('/users/batch/notify', { userIds, notification });
  }
}

export const userService = new UserService();
export default userService;